package greatwall.myreader;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;

import com.iximo.domain.Book;
import com.iximo.domain.Category;
import com.iximo.domain.Chapter;
import com.iximo.openAPI.impl.IximoOpenAPIGetImpl;
import com.iximo.util.*;

import android.util.Log;
import android.view.*;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class Getchapter extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.chapterlist);
        Intent intent=getIntent();
		String value=intent.getStringExtra("BookID");
		int bookID = Integer.parseInt(value);
        GetControls();
//        CreateListener();
        init(); 
        getChapter(bookID);
        set_title(bookID);
        LVResult.setOnItemClickListener(itemListener);
    }
   
    private TextView TVResult;
    private TextView title;
    private Button BTNSearch;
    private EditText ETSearch;
    private ListView LVResult;
    private ProgressDialog progressDialog;
    private SimpleAdapter listItemAdapter;  
    private ArrayList<HashMap<String,String > > listItem = null;  
    
    private void GetControls()
    {
    	TVResult = (TextView)findViewById(R.id.resultContent);
    	BTNSearch = (Button)findViewById(R.id.menu);
//    	ETSearch = (EditText)findViewById(R.id.searchContent);
    	LVResult = (ListView)findViewById(R.id.listchapter); 
    	title = (TextView)findViewById(R.id.title);
    }
    
    private OpenAPIClient XiMoClient = OpenAPIClientFactory.GetInstance();
    private IximoOpenAPIGetImpl Get = new IximoOpenAPIGetImpl();
    //点击每一个章节转到本章内容事件
    private OnItemClickListener itemListener = new OnItemClickListener(){
    	@Override
	    public void	onItemClick(AdapterView<?> parent, View view, final int position, long id) 
		{
    		int rowID = (int)id;
    		String chapterID = listItem.get(rowID).get("chapterID");
    		Intent in = new Intent();
    		in.putExtra("chapterID", chapterID);
    		in.setClass(Getchapter.this, chaptercontent.class);
    		startActivity(in);
    	} };
    private void CreateListener()
    {    	 
    	BTNSearch.setOnClickListener(btn1Listener);
    	
    }
    
    //按钮点击事件
    private OnClickListener btn1Listener = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			//开启progressDialog，显示等待框
			progressDialog = ProgressDialog.show(Getchapter.this, 
					"Loading...", "Please wait...", true, false);  
			
			//启动线程获取图书信息
			/*new Thread(){
				@Override
				public void run()
				{						
					try
					{
						//获取113277那本书的信息,并将标题封装成Message传送给Handler处理
						Message msg = new Message();
						Bundle b = new Bundle();
						b.putString("chapterlist", XiMoClient.get_book_chapters_list(113277, ""));
						msg.setData(b);
						//XiMoClient.get_message("inbox", 1, 30, "");
						Log.i("1", "end");
						handler.sendMessage(msg);						
					}
					catch(Exception e)
					{
						//没有获取到，发送异常消息
						Message msg = new Message();
						Bundle b = new Bundle();
						b.putString("chapterlist", "获取失败");
						msg.setData(b);
						handler.sendMessage(msg);
					}
				}
			}.start();*/
		}
	};
    private void getChapter(final int bookID){
    	progressDialog = ProgressDialog.show(Getchapter.this, 
				"Loading...", "Please wait...", true, false); 
    	new Thread(){
		
			public void run()
			{						
				try
				{
					//获取113277那本书的信息,并将标题封装成Message传送给Handler处理
					Message msg = new Message();
					Bundle b = new Bundle();
					b.putString("chapterlist", XiMoClient.get_book_chapters_list(bookID, ""));
					msg.setData(b);
					//XiMoClient.get_message("inbox", 1, 30, "");
					Log.i("1", "end");
					handler.sendMessage(msg);						
				}
				catch(Exception e)
				{
					//没有获取到，发送异常消息
					Message msg = new Message();
					Bundle b = new Bundle();
					b.putString("chapterlist", "获取失败");
					msg.setData(b);
					handler.sendMessage(msg);
				}
			}
    	
    	
    }.start();
    }
    private void set_title(int bookID)
	{
		try
		{
			//调用吸墨的API根据获取到的ID 获取对应书籍的信息
			String book_info=XiMoClient.get_book_info(bookID, "");
			InputStream inputStream = new ByteArrayInputStream(book_info.getBytes());
			Book   book=Get.getBookInfoData(inputStream);
			title.setText(book.getTitle());
			//获取到的信息对应的显示在界面上
			
		}
		catch (Exception e) 
		{
			// TODO: handle exception
			Log.i("Book_Detail_info", "获取不到数据");
		}	
	}
	private void init()
	{
		listItem = new ArrayList<HashMap<String,String > >();  
		listItemAdapter = new SimpleAdapter(getApplicationContext(),listItem,R.layout.listitem,
				new String[] { "title"},new int[]{R.id.itemtitle});
		LVResult.setAdapter(listItemAdapter);
		
	}
	
	//处理线程发送过来的消息
  
    private Handler handler = new Handler(){
    	@Override
    	public void handleMessage(Message msg)
    	{
    		try
    		{
	    		progressDialog.dismiss();
	    		String cl = msg.getData().getString("chapterlist");
	    		InputStream is = new ByteArrayInputStream(cl.getBytes());
	    		IximoOpenAPIGetImpl iximoimpl = new IximoOpenAPIGetImpl();
	    		
    			List<Chapter> chl = iximoimpl.getChapterData(is);
    			
    			for(int i = 0; i < chl.size(); i++)
    			{
    				//TVResult.append(chl.get(i).getTitle());
    				HashMap<String, String> map = new HashMap<String, String>();  
    				map.put("title", chl.get(i).getTitle());
    				map.put("chapterID",chl.get(i).getChapterID() + "");
    				listItem.add(map);
    			}
    			listItemAdapter.notifyDataSetChanged();
    		}
    		catch(Exception e)
    		{
    			TVResult.setText("erroraa");
    		}
    	}
    };


}